package red.lixiang.controller;

import red.lixiang.model.BaseInfo;
import red.lixiang.model.WeChatInfo;
import red.lixiang.service.CartService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.logging.Logger;

import static red.lixiang.base.APPCONST.WECHAT_INFO;

@Controller
public class CartController {

    private    final Logger logger = Logger.getLogger(CartController.class.getName());

    @Autowired
    private CartService cartService;

    @GetMapping("/cart/showCart")
    public String showCart(HttpServletRequest request, Model model ){
        logger.info("come in showCart");
        WeChatInfo weChatInfo = (WeChatInfo) request.getSession().getAttribute(WECHAT_INFO);
        BaseInfo baseInfo = cartService.getCartInfoByOpenId(weChatInfo.getOpenid());
        model.addAttribute("cartInfo",baseInfo.getObject());

        return "cart";
    }
    @GetMapping("/cart/addToCart/{cartId}")
    @ResponseBody
    public String addToCart(@PathVariable String cartId,
                            HttpServletRequest request){
        logger.info("come in addToCart");
        BaseInfo baseInfo = new BaseInfo();
        //先从session里面获取微信用户信息,提交订单的时候再检测会员信息
        WeChatInfo weChatInfo = (WeChatInfo) request.getSession().getAttribute(WECHAT_INFO);
        if(weChatInfo!=null){
          baseInfo=  cartService.addToCartByOpenId(cartId,weChatInfo.getOpenid());
        }else {
            //如果没有微信用户信息，应该不存在这种情况，对每个入口都加上微信号的获取
        }
        return JSON.toJSONString(baseInfo);
    }
    @GetMapping("/cart/deleteCart/{barCode}")
    @ResponseBody
    public String deleteCart(@PathVariable String barCode,
                            HttpServletRequest request){
        logger.info("come in deleteCart");
        BaseInfo baseInfo = new BaseInfo();
        //先从session里面获取微信用户信息,提交订单的时候再检测会员信息
        WeChatInfo weChatInfo = (WeChatInfo) request.getSession().getAttribute(WECHAT_INFO);
        if(weChatInfo!=null){
          baseInfo=  cartService.deleteCartByOpenId(barCode,weChatInfo.getOpenid());
        }else {
            //如果没有微信用户信息，应该不存在这种情况，对每个入口都加上微信号的获取
        }
        return JSON.toJSONString(baseInfo);
    }
}
